package servlet;

import service.ArticleService;
import service.CommentService;
import model.Article;
import model.Comment;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/articleDetail")
public class ArticleDetailServlet extends HttpServlet {
    private ArticleService articleService = new ArticleService();
    private CommentService commentService = new CommentService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            String articleIdStr = request.getParameter("id");
            if (articleIdStr == null || articleIdStr.trim().isEmpty()) {
                response.sendRedirect("articleList");
                return;
            }

            int articleId = Integer.parseInt(articleIdStr);
            Article article = articleService.getArticleDetail(articleId);
            if (article == null) {
                response.sendRedirect("articleList");
                return;
            }

            int page = 1;
            int pageSize = 5;
            String pageParam = request.getParameter("page");
            if (pageParam != null && !pageParam.isEmpty()) {
                try {
                    page = Integer.parseInt(pageParam);
                } catch (NumberFormatException e) {
                    page = 1;
                }
            }

            List<Comment> comments = commentService.getCommentsByArticle(articleId, page, pageSize);
            Map<String, Object> pageInfo = commentService.getCommentPageInfo(articleId, pageSize);

            // 设置请求属性
            request.setAttribute("article", article);
            request.setAttribute("comments", comments);
            request.setAttribute("currentPage", page);
            request.setAttribute("totalPages", pageInfo.get("totalPages"));
            request.setAttribute("totalCount", pageInfo.get("totalCount"));
            
            // 转发到 JSP 页面
            request.getRequestDispatcher("/WEB-INF/articleDetail.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("articleList");
        }
    }
}